﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MessageServer.pool
{
    public abstract class IDistributeObject : IPoolableObject
    {
        protected int _maxObjects;

        public IDistributeObject(int cnt)
        {
            _maxObjects = cnt;
        }

        public abstract int NoObjects { get; }
        //assumed that this is made thread safe. Thread is not handled here.
        public abstract void attach(object o);
    }

    class DistributionPool : StrictObjectPool
    {
        IList _objects;

        public DistributionPool(IPoolableObjectCreator creator) : base(creator)
        {
        }

        public DistributionPool(IPoolableObjectCreator creator, int waittime,
            int minobjects, int maxobjects) : base(creator, waittime, minobjects, maxobjects)
        {
        }

        protected override void objectadded(PoolObject obj)
        {
            if (_objects == null)
                _objects = new ArrayList();

            _objects.Add(obj);
        }

        private IDistributeObject findObjectToDistribute()
        {
            IDistributeObject ret = null;
            int cnt = Int32.MaxValue;
            //For now get the one with the minimum and assign to it.
            foreach (PoolObject obj in _objects)
            {
                IDistributeObject dist = obj.poolobject as IDistributeObject;
                if (cnt > dist.NoObjects)
                {
                    cnt = dist.NoObjects;
                    ret = dist;
                }
            }

            return ret;
        }

        public IDistributeObject attach(object o)
        {
            //have to see how to make this thread safe.
            IDistributeObject dist = findObjectToDistribute();
            dist.attach(o);
            return dist;
        }
    }
}
